package com.ruoyi.web.controller.product.service.Impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.DO.product.ProductCategoryDO;
import com.ruoyi.common.entity.VO.product.ProductCategorySearchVO;
import com.ruoyi.common.entity.VO.product.ProductCategoryVO;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryLinkMapper;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryMapper;
import com.ruoyi.web.controller.product.service.IBackProductCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class BackProductCategoryServiceImpl implements IBackProductCategoryService {

    @Resource
    private IBackProductCategoryMapper categoryMapper;

    @Resource
    private IBackProductCategoryLinkMapper linkMapper;

    @Override
    public List<ProductCategoryVO> searchCategoryList(ProductCategorySearchVO categorySearchVO) throws BusinessException {
        List<ProductCategoryVO> list = new ArrayList<>();
        try {
            categorySearchVO.setIsDelete(0);
            list = categoryMapper.searchCategoryList(categorySearchVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Ztree> searchCategoryTree(ProductCategorySearchVO productCategorySearchVO) {
        productCategorySearchVO.setIsEnable(1);
        productCategorySearchVO.setIsDelete(0);
        List<ProductCategoryVO> categoryList = categoryMapper.searchCategoryList(productCategorySearchVO);
        List<Ztree> ztrees;
        if (productCategorySearchVO.getProductId() != null) {
            List<Long> linkCategoryIdList = linkMapper.searchCategoryIdList(productCategorySearchVO.getProductId());
            ztrees = initZtree(categoryList, linkCategoryIdList);
        } else if (productCategorySearchVO.getCategoryIdStr() != null) {
            List<Long> linkCategoryIdList = Arrays.asList(Convert.toLongArray(productCategorySearchVO.getCategoryIdStr()));
            ztrees = initZtree(categoryList, linkCategoryIdList);
        } else {
            ztrees = initZtree(categoryList, null);
        }
        if(productCategorySearchVO.getIsSelect()!=null && productCategorySearchVO.getIsSelect() == 1){
            Ztree ztree = new Ztree();
            ztree.setId(0L);
            ztree.setpId(0L);
            ztree.setName("全部分类");
            ztree.setTitle("全部分类");
            ztrees.add(0,ztree);
        }
        return ztrees;
    }

    @Override
    public ProductCategoryVO getCategoryInfoById(Long categoryId) {
        return categoryMapper.getCategoryInfoById(categoryId);
    }

    @Override
    public int countCategory(ProductCategorySearchVO categorySearchVO) {
        return categoryMapper.countCategory(categorySearchVO);
    }

    @Override
    public boolean checkCategoryExistProduct(Long categoryId) {
        int result = categoryMapper.checkCategoryExistProduct(categoryId);
        return result > 0;
    }

    @Override
    public String checkCategoryNameUnique(ProductCategorySearchVO productCategorySearchVO) {
        Long categoryId = StringUtils.isNull(productCategorySearchVO.getCategoryId()) ? -1L : productCategorySearchVO.getCategoryId();
        ProductCategoryVO info = categoryMapper.checkCategoryNameUnique(productCategorySearchVO.getCategoryName(), productCategorySearchVO.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != categoryId.longValue()) {
            return Constants.FAIL;
        }
        return Constants.SUCCESS;
    }

    @Override
    public int insertCategory(ProductCategoryVO categoryVO) {
        ProductCategoryDO categoryDO = new ProductCategoryDO();
        categoryDO.setAncestors(getParentAncestors(categoryVO.getParentId()));
        categoryDO.setParentId(categoryVO.getParentId());
        categoryDO.setCategoryName(categoryVO.getCategoryName());
        categoryDO.setCoverUrl(categoryVO.getCoverUrl());
        categoryDO.setOrderNum(categoryVO.getOrderNum());
        categoryDO.setIsEnable(categoryVO.getIsEnable());
        categoryDO.setCreateTime(new Date());
        categoryDO.setCreateBy(categoryVO.getCreateBy());
        categoryDO.setIsDelete(0);
        int count = categoryMapper.insertSelective(categoryDO);
        return count;
    }

    @Override
    @Transactional
    public int updateCategory(ProductCategoryVO categoryVO) {
        ProductCategoryDO categoryDO = categoryMapper.selectByPrimaryKey(categoryVO.getId());
        if (categoryDO == null || categoryDO.getIsDelete() == 1) {
            throw new BusinessException("分类已被删除，请刷新后重试！");
        }
        String oldCategoryName = categoryDO.getCategoryName();
        String oldAncestors = categoryDO.getAncestors();
        categoryDO.setAncestors(getParentAncestors(categoryVO.getParentId()));
        categoryDO.setParentId(categoryVO.getParentId());
        categoryDO.setCategoryName(categoryVO.getCategoryName());
        categoryDO.setCoverUrl(categoryVO.getCoverUrl());
        categoryDO.setOrderNum(categoryVO.getOrderNum());
        categoryDO.setIsEnable(categoryVO.getIsEnable());
        categoryDO.setUpdateTime(new Date());
        categoryDO.setUpdateBy(categoryVO.getUpdateBy());
        updateCategoryChildren(categoryVO.getId(), categoryDO.getAncestors(), oldAncestors);
        //TODO:分类名称修改，商品表的分类拼接组合字段要同步更新
        if(!categoryDO.getCategoryName().equals(oldCategoryName)){
            AsyncManager.me().execute(AsyncFactory.productCategoryNameChangeEvent(categoryVO.getId()));
        }
        return categoryMapper.updateByPrimaryKeySelective(categoryDO);
    }

    @Override
    public int deleteCategoryById(Long id) {
        return categoryMapper.deleteCategoryById(id);
    }

    /**
     * 对象转分类树
     *
     * @param categoryList 分类列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<ProductCategoryVO> categoryList, List<Long> linkCategoryIdList) {
        List<Ztree> ztrees = new ArrayList<>();
        boolean isCheck = StringUtils.isNotNull(linkCategoryIdList);
        for (ProductCategoryVO categoryVO : categoryList) {
            if (Constants.SWITCH_ON.equals(categoryVO.getIsEnable())) {
                Ztree ztree = new Ztree();
                ztree.setId(categoryVO.getId());
                ztree.setpId(categoryVO.getParentId());
                ztree.setName(categoryVO.getCategoryName());
                ztree.setTitle(categoryVO.getCategoryName());
                if (isCheck) {
                    ztree.setChecked(linkCategoryIdList.contains(categoryVO.getId()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 获取上级分类的祖级列表
     *
     * @param parentId 上级分类ID
     * @return
     */
    private String getParentAncestors(Long parentId) {
        if (parentId > Constants.TOP_CATEGORY_ID) {
            //顶级分类
            ProductCategoryVO info = categoryMapper.getCategoryInfoById(parentId);
            if (info.getAncestors().equals(Constants.TOP_CATEGORY_ID.toString())) {
                return parentId.toString();
            } else {
                return info.getAncestors() + "," + parentId;
            }
        } else {
            return Constants.TOP_CATEGORY_ID.toString();
        }
    }

    /**
     * 修改子元素关系
     *
     * @param categoryId   被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateCategoryChildren(Long categoryId, String newAncestors, String oldAncestors) {
        List<ProductCategoryVO> children = categoryMapper.selectChildrenCategoryById(categoryId);
        if (children.size() > 0) {
            for (ProductCategoryVO child : children) {
                child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
            }
            categoryMapper.updateCategoryChildren(children);
        }
    }

    @Override
    public Long handleImport(Long parentId, String categoryName) {
        ProductCategoryVO info = categoryMapper.checkCategoryNameUnique(categoryName, parentId);
        if (info == null) {
            ProductCategoryDO categoryDO = new ProductCategoryDO();
            categoryDO.setAncestors(getParentAncestors(parentId));
            categoryDO.setParentId(parentId);
            categoryDO.setCategoryName(categoryName);
            categoryDO.setCoverUrl("");
            categoryDO.setOrderNum(0);
            categoryDO.setIsEnable(1);
            categoryDO.setCreateTime(new Date());
            categoryDO.setCreateBy("导入商品自动创建");
            categoryDO.setIsDelete(0);
            categoryMapper.insertSelective(categoryDO);
            return categoryDO.getId();
        }
        return info.getId();
    }
}
